import { OCRResult } from '../types/product';

// 模拟OCR识别服务
// 实际项目中需要替换为真实的OCR API调用
export const recognizeImage = async (imageFile: File): Promise<OCRResult> => {
  // 这里应该调用实际的OCR API
  // 返回模拟数据
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        date: new Date().toISOString().split('T')[0],
        rate: 4.33,
        netWorth: 1.0433,
        dailyProfit: 1.23
      });
    }, 1000);
  });
};

// 解析OCR结果
export const parseOCRResult = (text: string): Partial<OCRResult> => {
  const result: Partial<OCRResult> = {};

  // 日期匹配
  const dateMatch = text.match(/(\d{4})[-.年](\d{1,2})[-.月](\d{1,2})/);
  if (dateMatch) {
    result.date = `${dateMatch[1]}-${dateMatch[2].padStart(2, '0')}-${dateMatch[3].padStart(2, '0')}`;
  }

  // 收益率匹配
  const rateMatch = text.match(/年化[收益率]+[：:]\s*(\d+\.\d+)%/);
  if (rateMatch) {
    result.rate = parseFloat(rateMatch[1]);
  }

  // 净值匹配
  const netWorthMatch = text.match(/净值[：:]\s*(\d+\.\d+)/);
  if (netWorthMatch) {
    result.netWorth = parseFloat(netWorthMatch[1]);
  }

  // 万份收益匹配
  const dailyProfitMatch = text.match(/万份收益[：:]\s*(\d+\.\d+)/);
  if (dailyProfitMatch) {
    result.dailyProfit = parseFloat(dailyProfitMatch[1]);
  }

  return result;
};

// 验证OCR结果
export const validateOCRResult = (result: Partial<OCRResult>): string[] => {
  const errors: string[] = [];

  if (!result.date) {
    errors.push('未能识别日期信息');
  }

  if (!result.rate && !result.netWorth && !result.dailyProfit) {
    errors.push('未能识别任何收益相关信息');
  }

  return errors;
};